﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace hmc.im.service.core
{
    public class systemuserLogic
    {
        private string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        public systemuserEntity GetUser(string username)
        {
            systemuserEntity entity = null;
            string sql = "SELECT m.id,m.username,m.userpass,af.first_name,af.last_name,af.last_login,af.last_ip,m.last_exit,m.login_location,af.expired,af.market_id,af.industry_id FROM ze_adminfields af LEFT JOIN ze_members m ON af.member_id=m.id WHERE m.username=@username";
            MySqlDataReader dr = NSimple.Data.MySql.SqlHelper.ExecuteReader(ConnectionString, System.Data.CommandType.Text, sql, new MySqlParameter("@username", username));
            if (dr.Read())
            {
                entity = new systemuserEntity();
                entity.UserId = dr.GetInt32(0);
                entity.UserName = dr.GetString(1);
                entity.Password = dr.GetString(2);
                entity.LastLoginTime = dr.GetInt64(5);
                entity.LastIP = dr.GetString(6);
                entity.LastExitTime = dr.GetInt64(7);
                entity.LoginLocation = dr.GetInt16(8);
            }
            return entity;
        }

        public void UpdateUserLoginStatus(int userid, string ip)
        {
            string sql = "UPDATE `ze_members` SET last_login=unix_timestamp(),login_location=3,last_ip=@ip WHERE id=" + userid + ";";
            NSimple.Data.MySql.SqlHelper.ExecuteNonQuery(ConnectionString, System.Data.CommandType.Text, sql, new MySqlParameter("@ip", ip));
        }
    }

    public class systemuserEntity
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public int UserId { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 最后登录时间
        /// </summary>
        public long LastLoginTime { get; set; }

        /// <summary>
        /// 最后退出时间
        /// </summary>
        public long LastExitTime { get; set; }

        /// <summary>
        /// 登录平台，1前台2后台3客户端
        /// </summary>
        public int LoginLocation { get; set; }

        /// <summary>
        /// 最后登录IP
        /// </summary>
        public string LastIP { get; set; }
    }
}
